<template>
  <div class="my-approval-table">
    <el-dialog title="审批关系" :visible.sync="approvalTableVisible">
      <div class="top-mag">
        <div class="line-msg">
          AD账户：{{itemData.ad}}
          <span class="name-span">姓名：{{itemData.userNm}}</span>
        </div>
        <div class="line-msg">
          <span>部门：{{itemData.deptNm}}</span>
          <span class="btn">
            <span class="red" @click="delectItem()">删除</span>
            <span @click="addDatalist()">新增</span>
          </span>
        </div>
      </div>
      <el-table size="mini" :border="true" :data="gridData" @selection-change="tableSelectChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="ad" label="AD账户"></el-table-column>
        <el-table-column property="userNm" label="姓名"></el-table-column>
        <el-table-column property="deptNm" label="部门" width="260"></el-table-column>
        <el-table-column label="审批关系">
          <template slot-scope="scope">
            <span>{{scope.row.category == "DIRECT_LEADER" ? '直线' : '虚线'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="审批权重">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.weight"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="savethisData()">保 存</el-button>
        <el-button size="mini" @click="approvalTableVisible = false">取 消</el-button>
      </div>
      <el-dialog class="add-usemsg" width="35%" title="新增审批人员" :visible.sync="innerVisible" append-to-body>
        <div class="item-complete">
          <span>请选择人员：</span>
          <el-autocomplete
            size="mini"
            v-model="state"
            value-key="showText"
            :fetch-suggestions="querySearchAsync"
            placeholder="请输入AD或姓名"
            @select="handleSelect"
          ></el-autocomplete>
        </div>
        <div class="item-complete">
          <span>审批关系：</span>
          <el-select size="mini" v-model="cvalue" @change="selectChange" placeholder="请选择">
            <el-option
              v-for="(item) in optionData"
              :key="item.value"
              :label="item.lable"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="commitcomplete()">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import Vue from "vue";
import {
  getrelationLists,
  saveRelationData,
  getByAdOrNmData
} from "@/api/getData";
import { alertMessage } from '@/config/myUtil';
import { Table, TableColumn, Autocomplete } from "element-ui";
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Autocomplete);
export default {
  name: "ApprovalTable",
  data() {
    return {
      approvalTableVisible: false,
      innerVisible: false,
      gridData: [],
      itemData: {},
      optionData: [
        { lable: "直线", value: "DIRECT_LEADER" },
        { lable: "虚线", value: "SPEC_LEADER" }
      ],
      state: "",
      cvalue: "",
      addItem: {},
      delectList: []
    };
  },
  methods: {
    async querySearchAsync(queryString, cb) {
      try {
        let data = await getByAdOrNmData({ key: queryString });
        data.map((item)=>{
          item.showText = `${item.userNm}—${item.deptNm}`;
        });
        cb(data);
      } catch (error) {
        cb([]);
      }
    },
    async initData(ad) {
      try {
        let data = await getrelationLists({ ad: ad });
        this.gridData = data;
      } catch (error) {
        console.log(error);
      }
    },
    async savethisData() {
      try {
        var savearr = [];
        if (this.gridData.length > 0) {
          this.gridData.map((item, index) => {
            savearr.push({
              relationId: "",
              createTime: "",
              ad: this.itemData.ad,
              associateAd: item.ad,
              category: item.category,
              weight: item.weight
            });
          });
        } else {
          savearr.push({
            relationId: "",
            createTime: "",
            ad: this.itemData.ad,
            associateAd: "",
            category: "",
            weight: ""
          });
        }
        var anum = 0;
        savearr.map((el)=>{
          anum += Number(el.weight) || 0
        });
        if(anum != 100){
          alertMessage('请保证审批权重为100！','warning');
          return
        }
        let data = await saveRelationData(savearr);
        this.approvalTableVisible = false;
        if (data == 1) {
          this.$emit('initThisData');
          alertMessage('保存成功!','success');
        } else {
          alertMessage('保存失败','warning');
        }
      } catch (error) {
        console.log(error);
      }
    },    
    changestaus(item) {
      this.itemData = item;
      this.approvalTableVisible = true;
      this.initData(item.ad);
    },
    tableSelectChange(selList) {
      this.delectList = selList;
    },
    delectItem() {
      if (this.delectList.length > 0) {
        this.gridData.map((item, index) => {
          item.isDelect = false;
          this.delectList.map(cte => {
            if (item.ad == cte.ad) {
              item.isDelect = true;
            }
          });
        });
        var arr = [];
        this.gridData.map((item, index) => {
          if (!item.isDelect) {
            arr.push(item);
          }
        });
        this.gridData = JSON.parse(JSON.stringify(arr));
      } else {
        alertMessage('请选择要删除的人!','warning');
      }
    },
    addDatalist() {
      this.addItem = {};
      this.cvalue = "";
      this.state = "";
      var array = this.gridData;
      var isdele = true;
      for (var index = 0; index < array.length; index++) {
        if (array[index].category == "DIRECT_LEADER") {
          isdele = false
          this.optionData = [{ lable: "虚线", value: "SPEC_LEADER" }];
          this.cvalue = "SPEC_LEADER";
          break;
        }
      }
      if(isdele){
        this.optionData = [
          { lable: "直线", value: "DIRECT_LEADER" },
          { lable: "虚线", value: "SPEC_LEADER" }
        ];
        this.cvalue = "DIRECT_LEADER";
      }
      this.innerVisible = true;
    },
    handleSelect(item) {
      this.addItem = {
        ad: item.ad,
        userNm: item.userNm,
        deptNm: item.deptNm,
        category: this.cvalue,
        weight: 0
      };
    },
    selectChange() {
      this.addItem.category = this.cvalue;
    },
    commitcomplete() {
      var _aditem = this.addItem;
      if (_aditem.ad && _aditem.category) {
        _aditem.weight = _aditem.category == "DIRECT_LEADER" ? 100 : 0;        
        var pass = true;
        this.gridData.map((item, index) => {
          if (item.ad == _aditem.ad) {
            pass = false;
          }
        });
        if (pass) {
          this.gridData.push(_aditem);
          this.innerVisible = false;
        } else {
          alertMessage('要添加的人已经存在！','warning');
        }
      } else {
        alertMessage('选择人员和关系！','warning');
      }
    }
  }
};
</script>
<style lang="less" scoped>
@import url("../less/approvalTable.less");
</style>